﻿using System;
using System.Collections.Generic;
using NHibernate;

namespace AiFrame.InterfaceLib.Data.Access.NHibernateAccess
{
    /// <summary>
    /// A basic data access class for NHibernate with common functions.
    /// </summary>
    /// <typeparam name="T">The type of the data object.</typeparam>
    /// <typeparam name="ID">The type of the ID value.</typeparam>
    public class BasicDaoNHibernate<T, ID> : IBasicDao<T, ID>
    {
        /// <summary>
        /// The current session.
        /// </summary>
        protected ISession _session;

        /// <summary>
        /// The type.
        /// </summary>
        private Type _persitentType = typeof(T);

        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="session"></param>
        public BasicDaoNHibernate(ISession session)
        {
            _session = session;
        }
        
        public virtual IList<T> FindAll()
        {
            IList<T> all = _session.CreateCriteria(_persitentType).List<T>();
            return all;
        }
                
        public virtual T FindByID(ID id)
        {
            T businessObject = _session.Load<T>(id);
            return businessObject;
        }

        public virtual void SaveOrUpdate(T item)
        {
            _session.BeginTransaction();
            _session.SaveOrUpdate(item);
            _session.Transaction.Commit();
        }

        public virtual void Delete(T item)
        {
            _session.BeginTransaction();
            _session.Delete(item);
            _session.Transaction.Commit();
        }

        public virtual void Delete(ID id)
        {
            T businessObject = FindByID(id);

            Delete(businessObject);
        }

        public virtual void Refresh(T item)
        {
            _session.Refresh(item);
        }

    }
}